import type { RegisterResponseType } from './types';
import { useState } from 'react'
import useRequest from '../../hooks/useRequest'
import { useNavigate } from 'react-router-dom';
import { message } from '../../utils/message';

const Register = () => {
  const navigate = useNavigate();
  const [phoneNumber, setPhoneNumber] = useState('')
  const [password, setPassword] = useState('')
  const [userName, setUserName] = useState('')
  const [confirmPassword, setConfirmPassword] = useState('')

  const { request } = useRequest<RegisterResponseType>({ manual: true })
  const handleSubmit = () => {
    if (!userName) {
      message('用户名不得为空！');
      return;
    }
    if (!phoneNumber) {
      message('手机号码不得为空！');
      return;
    }
    if (!password) {
      message('密码不得为空！');
      return;
    }
    if (password.length < 6) {
      message('密码至少为六位！');
      return;
    }
    if (password !== confirmPassword) {
      message('两次输入密码不一致！');
      return;
    }
    request({
      url: '/register.json',
      method: 'POST',
      data: {
        phone: phoneNumber,
        password: password,
        user: userName
      }
    }).then((data) => {
      if (data?.success) {
        navigate('/account/login')
      }
    }).catch((e: any) => {
      message(e?.message || '未知异常')
    });
  }

  return (
    <>
      <div className="form">
        <div className="form-item">
          <div className="form-item-title">用户名</div>
          <input
            className="form-item-content"
            value={userName}
            placeholder="请输入用户名"
            onChange={(e) => { setUserName(e.target.value) }}
          />
        </div>
        <div className="form-item">
          <div className="form-item-title">手机号</div>
          <input
            className="form-item-content"
            value={phoneNumber}
            placeholder="请输入手机号码"
            onChange={(e) => { setPhoneNumber(e.target.value) }}
          />
        </div>
        <div className="form-item">
          <div className="form-item-title">密码</div>
          <input
            type="password"
            className="form-item-content"
            value={password}
            placeholder="请输入密码"
            onChange={(e) => { setPassword(e.target.value) }}
          />
        </div>
        <div className="form-item">
          <div className="form-item-title">确认密码</div>
          <input
            type="password"
            className="form-item-content"
            value={confirmPassword}
            placeholder="请再次输入密码"
            onChange={(e) => { setConfirmPassword(e.target.value) }}
          />
        </div>
      </div>
      <div className="submit" onClick={handleSubmit} >
        注册
      </div>
    </>
  )
}

export default Register